package mblog.plugins;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * http 转https filter
 * @author wuyb
 *
 */
public class Http2HttpsFilter implements Filter{
	
	private URI reqUri;
	
	private URI httpsUri;
	
	public Http2HttpsFilter() {

    }

    @Override
	public void destroy() {
		
	}

    @Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse res = (HttpServletResponse)response;
			
		//获取请求协议
		String scheme = request.getScheme();
		
		//http的url换成https的url
		try{
			if(req.getQueryString()!=null && !"".equals(req.getQueryString())){
				reqUri = new URI(req.getRequestURL()+"?"+req.getQueryString());
			}else{
				reqUri = new URI(req.getRequestURL().toString());
			}
			
			httpsUri = new URI("https", reqUri.getUserInfo(),
	                reqUri.getHost(), reqUri.getPort(), reqUri.getPath(),
	                reqUri.getQuery(), reqUri.getFragment());
			System.out.println("httpsUri : "+httpsUri);
		}catch(URISyntaxException e){
			e.printStackTrace();
		}
		
		//http 协议的链接  重定向到https 新链接上
		if(scheme.equals("http")){
    		 res.sendRedirect(httpsUri.toString());
    		 return;
			
		}else{
			chain.doFilter(req, res);
		}
	}

    @Override
	public void init(FilterConfig fConfig) throws ServletException {
		
	}
}
